package us.clubadvocate.client;

import java.util.HashMap;

import us.clubadvocate.client.index.IndexProvider;
import us.clubadvocate.client.splash.SplashProvider;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootLayoutPanel;

public class ClubAdvocatorController 
  implements EntryPoint, ValueChangeHandler<String>
{
  private static final String defaultPage = "splash";
  private static final HashMap<String, AsyncPortalProvider> providers 
    = new HashMap<String, AsyncPortalProvider>();
  
  // ---------------------------------------------------------------------------
  
  static
  {
    registarProviders(new IndexProvider());
    registarProviders(new SplashProvider());
  }
  
  // ---------------------------------------------------------------------------
  
  HashMap<String, Portal> portals = new HashMap<String, Portal>();
  
  String currentToken;
  Portal loadedPortal;
  
  // ---------------------------------------------------------------------------
  // ---------------------------------------------------------------------------
  
  public static void registarProviders(AsyncPortalProvider factory)
  {
    providers.put(factory.getName(), factory);
  }
  
  // ---------------------------------------------------------------------------
  
  @Override
  public void onModuleLoad()
  {
    AsyncPortalProvider.setController(this);
    History.addValueChangeHandler(this);
    History.fireCurrentHistoryState();
  }
  
  // ---------------------------------------------------------------------------
  
  @Override
  public void onValueChange(ValueChangeEvent<String> event)
  {
    String value = event.getValue().trim();
    if((value == null) || value.isEmpty() )
      value = defaultPage;
    
    if(value.equals(currentToken))
    {
      loadedPortal.onStateChange(value);
    }
    else
    {
      Portal p = portals.get(value);
      if(p != null)
      {
        present(p, value);
      }
      else
      {
        AsyncPortalProvider ap = providers.get(value);
        if(ap == null)
          throw new IllegalStateException();
        ap.startAsync();
      }
    }
  }
  
  // ---------------------------------------------------------------------------
  
  public void present(Portal portal, String portalToken)
  {
    RootLayoutPanel root = RootLayoutPanel.get();
    root.clear();
    root.add(portal.getView());
    currentToken = portalToken;
    loadedPortal = portal;
  }
  
  // ---------------------------------------------------------------------------
}
